<template>
  <div class="station-form-container">
    <n-card :bordered="false">
      <!-- 页面标题 -->
      <h2>{{ isEdit ? '编辑站点' : '添加站点' }}</h2>

      <!-- 站点表单 -->
      <n-form ref="formRef" :model="stationForm" :rules="formRules" layout="vertical" label-placement="left" label-width="120px" :style="{ maxWidth: '300px' }">
        <n-form-item label="站点名称" path="name">
          <n-input v-model:value="stationForm.name" placeholder="请输入站点名称" />
        </n-form-item>

        <n-form-item label="站点类型" path="type">
          <n-select v-model:value="stationForm.type" placeholder="请选择站点类型" :options="stationTypes" />
        </n-form-item>

        <n-form-item label="站点状态" path="status">
          <n-select v-model:value="stationForm.status" placeholder="请选择站点状态" :options="stationStatuses" />
        </n-form-item>

        <n-form-item label="X坐标" path="x">
          <n-input-number v-model:value="stationForm.x" :min="0" :max="10000" placeholder="请输入X坐标（0-10000）" />
        </n-form-item>

        <n-form-item label="Y坐标" path="y">
          <n-input-number v-model:value="stationForm.y" :min="0" :max="10000" placeholder="请输入Y坐标（0-10000）" />
        </n-form-item>

        <n-form-item label="站点描述" path="description">
          <n-input v-model:value="stationForm.description" type="textarea" placeholder="请输入站点描述（选填）" :autosize="{ minRows: 3, maxRows: 6 }" />
        </n-form-item>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <n-button @click="handleCancel">取消</n-button>
          <n-button type="primary" :loading="loading" @click="handleSubmit">{{ isEdit ? '更新' : '提交' }}</n-button>
        </div>
      </n-form>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { NCard, NForm, NFormItem, NInput, NSelect, NInputNumber, NButton, useMessage } from "naive-ui";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { API_URLS } from '../../utils/apiConfig';

const router = useRouter();
const route = useRoute();
const message = useMessage();

// 状态管理
const loading = ref(false);
const isEdit = ref(false);

// 声明formRef
const formRef = ref(null);
const stationId = ref(null);

// 表单数据模型
const stationForm = reactive({
  name: "",
  type: "",
  status: "",
  x: 0,
  y: 0,
  description: "",
});

// 表单验证规则
const formRules = {
  name: { required: true, message: "请输入站点名称", trigger: "blur", min: 1, max: 50 },
  type: [{ required: true, message: "请选择站点类型", trigger: "change" }],
  status: [{ required: true, message: "请选择站点状态", trigger: "change" }],
  x: { required: true, type: "number", min: 0, max: 10000, message: "X坐标应在0到10000之间", trigger: "change" },
  y: { required: true, type: "number", min: 0, max: 10000, message: "Y坐标应在0到10000之间", trigger: "change" },
  description: { max: 255, message: "站点描述长度不能超过255个字符", trigger: "blur" },
};

// 站点类型选项
const stationTypes = [
  { label: "节点", value: "node" },
  { label: "充电站", value: "charging" },
  { label: "入库站", value: "inbound" },
  { label: "出库站", value: "outbound" },
  { label: "分拣站", value: "sorting" },
  { label: "维修站", value: "maintenance" },
  { label: "其他", value: "unknown" },
];

// 站点状态选项
const stationStatuses = [
  { label: "空闲", value: "idle" },
  { label: "运行中", value: "running" },
  { label: "充电中", value: "charging" },
  { label: "维护中", value: "maintenance" },
  { label: "未知", value: "unknown" },
];

// 检查是否为编辑模式
onMounted(() => {
  // 从路由参数中获取站点ID
  const id = route.params.id;
  if (id) {
    isEdit.value = true;
    stationId.value = id;
    fetchStationDetail(); // 加载站点详情
  }
});

// 获取站点详情（编辑模式）
const fetchStationDetail = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${API_URLS.map_node.detail}/${stationId.value}`, {
      params: {},
    });

    if (response.data.code === 200) {
      const stationData = response.data.data;
      // 填充表单数据
      stationForm.name = stationData.name || "";
      stationForm.type = stationData.type || "";
      stationForm.status = stationData.status || "";
      stationForm.x = stationData.x || 0;
      stationForm.y = stationData.y || 0;
      stationForm.description = stationData.description || "";
    } else {
      message.error(`获取站点详情失败: ${response.data.msg || "未知错误"}`);
      router.push("/AGV/Station_list");
    }
  } catch (error) {
    message.error(`网络错误: 无法获取站点详情 (${error.message})`);
    router.push("/AGV/Station_list");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 验证表单数据
    await formRef.value.validate();
    loading.value = true;

    const formData = {
      name: stationForm.name,
      type: stationForm.type,
      status: stationForm.status,
      x: stationForm.x,
      y: stationForm.y,
      description: stationForm.description,
    };

    let response;
    if (isEdit.value) {
      // 编辑模式 - PUT请求
      response = await axios.put(
        `${API_URLS.map_node.update}`,
        { ...formData, id: stationId.value },
        {
          params: {},
        }
      );
    } else {
      // 添加模式 - POST请求
      response = await axios.post(`${API_URLS.map_node.create}`, formData, {
        params: {},
      });
    }

    if (response.data.code === 200) {
      message.success(`站点${isEdit.value ? "更新" : "创建"}成功:${response.data.msg}`);
      router.push("/AGV/Station_list");
    } else {
      message.error(`站点${isEdit.value ? "更新" : "创建"}失败: ${response.data.msg}`);
    }
  } catch (error) {
    if (error.response) {
      // 后端有响应（如400/401/402等状态码）
      const statusCode = error.response.status; // HTTP状态码（如402）
      const detail = error.response.data.detail || "未知错误信息"; // 提取detail字段

      // 后端返回错误码 及错误信息
      message.error(`站点${isEdit.value ? "更新" : "创建"}失败: ${detail} (状态码: ${statusCode})`);
    } else if (error.request) {
      message.error("网络错误: ", error.message);
    } else {
      message.error("其他错误: " + error.message);
    }
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  router.push("/AGV/Station_list");
};
</script>

<style scoped>
.station-form-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.station-form-container h2 {
  margin: 0 0 20px 0;
  font-size: 20px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>
